package com.reggie.controller.user;

import com.reggie.entity.Dish;
import com.reggie.result.R;
import com.reggie.service.DishService;
import com.reggie.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品浏览接口")
public class DishController {
    @Autowired
    private DishService dishService;

    //注入Redis
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public R<List<DishVO>> list(Long categoryId) {
        String key = "dish_"+categoryId;
        //获取Redis中的缓存菜品
        List<DishVO> list= (List<DishVO>) redisTemplate.opsForValue().get(key);
        //判断缓存里面 有没有获取到菜品
        if(list!=null &&list.size()>0){
            //如果获取到菜品就直接返回
            return R.success(list);
        }
        //没有在缓存中查到数据 就去数据库再次查询
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(Dish.ON);

        list = dishService.listWithFlavor(dish);

        //将在数据库中查询到的数据 再次存放到缓存中
        redisTemplate.opsForValue().set(key,list);


        return R.success(list);
    }

}
